package com.ash.dao.impl;


import com.ash.dao.IStudentDao;
import com.ash.domain.Student;
import com.ash.util.ConnectionsUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;

import java.util.List;


/**
 * @encoding : UTF-8
 * @Time : 2020/12/3 21:28
 * @Author : Chen Chao
 * @File : connection.com.ash.dao.impl.StudentDaoImpl.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 */
public class StudentDaoImpl implements IStudentDao {
   public static QueryRunner qr = new QueryRunner(ConnectionsUtil.getDataSource());
    @Override
    public boolean add(Student student) {
        String sql = "insert into student (id, name, age) value (?,?,?)";
        int update=0;
        try {
            update= qr.update(sql, student.getId(), student.getName(), student.getAge());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return update!=0;
    }

    @Override
    public Student select(int id) {
        String sql="Select * from student where id=?";
        List<Student> students ;
        try {
            students = qr.query(sql, new BeanListHandler<>(Student.class), id);
            if(students!=null&&students.size()!=0){
                return students.get(0);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();

        }
        return null;

    }

    @Override
    public List<Student> selectAll() {
        String sql="Select * from student";
        try {
            return  qr.query(sql, new BeanListHandler<>(Student.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean delete(Student student) {
        Integer id = student.getId();
        if (select(id) == null) {
            return true;
        }

        int update=0;
        String sql="delete from student where id=?";
        try {
             update = qr.update(sql, id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return update!=0;
    }

    @Override
    public boolean modify(Student student) {
        Integer id = student.getId();
        if (select(id) == null) {
            System.out.println("不存在记录");
            return false;
        }

        int update=0;
        String sql="update student set name=?,age=? where id=?";
        try {
            update = qr.update(sql, student.getName(), student.getAge(), id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return update!=0;
    }
}
